package com.ryx.exception.handler;

import com.ryx.exception.GlobalException;
import com.ryx.exception.code.BaseResponseCode;
import com.ryx.utils.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.List;

/**
 * @BelongsPackage: com.ryx.exception.handler
 * @Author: 容永轩
 * @CreateTime: 2020-11-06
 * @Description:
 */
@RestControllerAdvice
@Slf4j
public class RestExceptionHandler {

    //监控最大异常
    @ExceptionHandler(Exception.class)
    public DataResult handleException(Exception e){

        log.error("HandlerException...:{}",e.getMessage());

        return DataResult.getResult(BaseResponseCode.SYSTEM_ERROR);
    }

    //监控全局异常
    @ExceptionHandler(GlobalException.class)
    public DataResult handleGlobalException(GlobalException e){
        log.error("GlobalException:{}",e.getMessage());

        //具体流程看testController中的testGlobalException()测试方法
        return DataResult.getResult(e.getCode(),e.getMsg());
    }

    //监控检验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public DataResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e){

        log.error("MethodArgumentNotValidException:AllErrors:{} MethodArgumentNotValidException:{}",e.getBindingResult().getAllErrors(),e.getMessage());
        String msg = null;
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        for (ObjectError allError : allErrors) {
            msg = allError.getDefaultMessage();
            break;
        }

        return DataResult.getResult(BaseResponseCode.VALIDATOR_ERROR.getCode(),msg);

    }
    //无权限异常
    @ExceptionHandler(UnauthorizedException.class)
    public DataResult unauthorizedException(UnauthorizedException e){
        log.error("UnauthorizedException:{}",e.getMessage());

        return DataResult.getResult(BaseResponseCode.NOT_PERMISSION);
    }

    //超出文件最大值异常
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public DataResult maxUploadSizeExceededException(MaxUploadSizeExceededException e){
        log.error("MaxUploadSizeExceededException={}",e.getMessage());
        return  DataResult.getResult(BaseResponseCode.FILE_TOO_LARGE);
    }



}
